﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using CantinhodaCegonha.Models;
using Data.Repositories;
using Domain;

namespace CantinhodaCegonha.Controllers
{
    public class AccountController : Controller
    {

        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    UserRepository rep = new UserRepository();
                    //FormsAuthentication.SetAuthCookie(rep.GetUserByEmail(model.UserName).Nome, model.RememberMe);

                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                       model.UserName,
                       DateTime.Now,
                       DateTime.Now.AddMinutes(60),
                       model.RememberMe,
                       rep.GetUserByEmail(model.UserName).Nome,
                       FormsAuthentication.FormsCookiePath);

                    // Encrypt the ticket.
                    string encTicket = FormsAuthentication.Encrypt(ticket);

                    // Create the cookie.
                    Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
                    
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                List<Filho> lstf = new List<Filho>();
                if (!model.TentarEngravidar)
                {
                    bool temfilho = false;
                    foreach (FilhosRegisto item in model.filhos)
                    {
                        if (item.Nome != null && item.Genero != null && item.DataNascimento != null)
                        {
                            temfilho = true;
                            lstf.Add(new Filho
                            {
                                Nome = item.Nome,
                                Activo = true,
                                DataNascimento = item.DataNascimento.Value,
                                Foto = item.Foto,
                                Genero = item.Genero,
                                DataFormatada = item.DataNascimento.Value.ToLongDateString()
                            });
                        }
                    }
                    if (!temfilho)
                    {
                        ModelState.AddModelError("", "Tem de indicar o Nome, Data de nascimento (data prevista do parto) e o género do seu filho.");
                        return View(model);
                    }
                    
                }
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, false, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    //Adicionar informaçoes adicionais ao user criado
                    UserRepository rep = new UserRepository();
                    rep.InsertUserRegisto(model.Email, Request.ServerVariables["REMOTE_ADDR"],
                                            model.SouPai, model.EmailParceiro, model.TentarEngravidar,
                                            model.Newsletter,lstf,model.Foto );

                    ////Antigo
                    //FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);

                    ////Novo
                    //FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                    //   model.Email,
                    //   DateTime.Now,
                    //   DateTime.Now.AddMinutes(60),
                    //   false,
                    //   rep.GetUserByEmail(model.Email).Nome,
                    //   FormsAuthentication.FormsCookiePath);

                    //// Encrypt the ticket.
                    //string encTicket = FormsAuthentication.Encrypt(ticket);

                    //// Create the cookie.
                    //Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

                    //return RedirectToAction("Index", "Home");
                    return RedirectToAction("ConfirmaRegisto", "Account");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "A password actual está incorrecta ou a nova password é invalida. Por favor corriga os erros e tente novamente.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        public ActionResult RecoverPassword()
        {
            //Faz post para RecoverPasswordQuestions
            return View();
        }

        [HttpPost]
        public ActionResult RecoverPasswordQuestions(string email)
        {
            return View();
        }

        [HttpPost]
        public ActionResult RecoverPasswordQuestions(string email,List<string> respostas)
        {
            //Faz post para ele proprio, se as respostas estiverem certas vai para recoverpasswordsuccess
            return View();
        }

        public ActionResult RecoverPasswordSuccess(string email)
        {
            return View();
        }

        public ActionResult CheckAvailability(string email)
        {
            UserRepository rep = new UserRepository();
            return Json(rep.EmailDisponivel(email));
        }

        public ActionResult ConfirmaRegisto()
        {
            return View();
        }

        public ActionResult Activate(string username, string key)
        {
            UserRepository _user = new UserRepository();
            if (_user.ActivateUser(username, key) == false)
                return RedirectToAction("Index", "Home");
            else
                return RedirectToAction("LogOn");
            //Data.Utils.MailTools.EnviaMailRegistoTeste(username, key);
            //return RedirectToAction("Index", "Home");
        }


        public ActionResult UserDetails(int id)
        {
            UserRepository user = new UserRepository();
            //return View(user.GetUserByEmail(User.Identity.Name));
            return View(user.GetUserByUserID(id));
        }

        [Authorize]
        public ActionResult MyDetails(int id)
        {
            UserRepository user = new UserRepository();
            return View(user.GetUserByEmail(User.Identity.Name));
        }

        [Authorize]
        [HttpPost]
        public ActionResult MyDetails(User user)
        {
            //gravar bd
            return View(user);
        }


        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "O email introduzido já existe. Por favor indique outro email.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "O email introduzido já existe. Por favor indique outro email.";

                case MembershipCreateStatus.InvalidPassword:
                    return "A password introduzida é inválida. Por favor introduza outra password.";

                case MembershipCreateStatus.InvalidEmail:
                    return "O email introduzido é inválido. Por favor indique outro email.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
